const express = require('express')
const path = require('path')
const fs = require('fs')
const formidable = require('formidable')

const app = express()

////跨域处理
app.all('*', function(req, res, next) {
	res.header('Access-Control-Allow-Origin', '*');
	res.header('Access-Control-Allow-Headers', 'Content-Type');
	res.header('Access-Control-Allow-Methods', '*');
	//允许客户端发送跨域请求时携带cookie信息
	res.header('Access-Control-Allow-Credentials', true);
	res.header('Content-Type', 'application/json;charset=utf-8');
	next();
});

app.post('/login', (req, res) => {
	//创建表单解析对象
	var form = formidable.IncomingForm()
	//解析表单
	form.parse(req, (err, fields, file) => {
		//接收客户端传递过来的用户名和密码
		const {username,password} = fields
		//用户名密码比对
		if(username == 'itheima' && password == '123456') {
			//设置session
//			req.session.isLogin = true
			res.send({
				message: '登录成功'
			})
		} else {
			res.send({
				message: '登录失败，用户名或密码错误'
			})

		}

	})

})

app.get('/test', function(req, res) {
	const result = 'fn({name:"zhansgan",age:13})'
	res.send(result)
})

app.get('/better', function(req, res) {
	/*	console.log(req.query)
		//接收客户端传递过来的函数名称
		const fnName=req.query.callback
		//可能从数据库中查询到数据返回给客户端，返回的前需要把数据转为json字符串
		const data=JSON.stringify({name:'张三'})
		//将函数名称对应的函数调用代码返回给客户端
		const result =  fnName+'('+data+')'
	    res.send(result)     */

	//相当于执行了以上的代码，优化方案
	res.jsonp({
		name: "lisi",
		age: 20
	})

})

//app.all('*', function(req, response, next) {
////设置允许跨域的域名，*代表允许任意域名跨域
//response.header("Access-Control-Allow-Origin", "*");
////允许跨域请求的请求头header类型，如果自定义了一个header，加入到其中就行，比如mytoken
//response.header("Access-Control-Allow-Headers", "X-Requested-With");
////跨域允许的请求方式
//response.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
////设置响应头信息
//response.header("X-Powered-By",' 3.2.1')
//response.header("Content-Type", "application/json;charset=utf-8");
//
//next();
//});

app.get('/cross', (req, res) => {
	//1.允许哪些客户端访问我
	//*  代表所有的客户端访问我
	res.header('Access-Control-Allow-Origin', '*');
	//2.允许客户端使用哪些请求方法访问我
	res.header('Access-Control-Allow-Methods', 'get,post');
})

var server = app.listen(10004, '192.168.0.101');